﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
using System.Data.Entity;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using EntityFramework.Extensions;
namespace Webcar.Controllers
{
    
    public partial class SecController : BaseControler
    {
        public ActionResult List()
        {
            return View();
        }

        public ActionResult ListPartialView(string id)
        {
            return PartialView();
        }
        public ActionResult Delete(string id)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑安全事故);
            using (var DB = new WebcarContext())
            {
                var model = DB.SEC_RECORD.Find(id);
                if (model != null)
                {
                    DB.SEC_RECORD.Remove(model);
                    DB.SEC_PAY_DETAIL.Delete(a => a.SEC_NO == id);
                    DB.SEC_PHOTO.Delete(a => a.SEC_NO == id);
                    DB.SaveChanges();
                    return Success("List", "Sec", new { id = model.SEC_DEPT });
                }
                else
                {
                    return Success("List", "Sec");
                }
            }
            
        }

        public ActionResult Export()
        {
            GridViewSettings settings = new GridViewSettings();
            settings.Name = "gridView";
            settings.Columns.Add("record_no", "牌照号");
            settings.Columns.Add("driver_name", "驾驶员");
            settings.AddChildDeptColumn(fieldname: "dept_code", caption: "单位（部门）");
            //settings.AddDeptColumn(fieldname:"dept_code");

            settings.Columns.Add("loss_money", "损失金额");
            settings.Columns.Add("sec_date", "事故", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.AddSecTypeColumn();
            settings.AddSecKindColumn();
            settings.AddSecDutyColumn();

            settings.Columns.Add("sec_place", "事故地点");
            settings.Columns.Add("end_flag", "是否结案");
            var data = UserDataProvider.GetSecList(this.RouteData).ToDataTable();
            return GridViewExtension.ExportToXls(settings, data, "安全事故");

            //return RedirectToAction("List", "Car");
        }
        public ActionResult ExportSummary(DateTime? start_date, DateTime? end_date, string check_report)
        {
            var table = GetSummaryData(start_date, end_date, check_report);
            if (table == null)
                return View("SecSummaryList");
            GridViewSettings settings = new GridViewSettings();
            settings.Name = "gridView";
            settings.Columns.Add("deptname", "单位名称");
            settings.Columns.Add("nums", "事故次数");
            settings.Columns.Add("loss", "事故损失");
            settings.Columns.Add("fm", "事故赔款");
            settings.Columns.Add("qs", "轻伤");
            settings.Columns.Add("zs", "重伤");
            settings.Columns.Add("sw", "死亡");
            settings.Columns.Add("sum_injury", "伤亡合计");
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "nums").DisplayFormat = "n0";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "loss").DisplayFormat = "c";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "fm").DisplayFormat = "c";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "qs").DisplayFormat = "n0";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "zs").DisplayFormat = "n0";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "sw").DisplayFormat = "n0";
            settings.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "sum_injury").DisplayFormat = "n0";
            settings.Settings.ShowFooter = true;
            return GridViewExtension.ExportToXls(settings, table, "安全事故统计");
        }
        DataTable GetSummaryData(DateTime? start_date, DateTime? end_date, string check_report)
        {
            if (start_date == null || end_date == null)
            {
                DateTime s = DateTime.Now.AddYears(-1);
                DateTime e = DateTime.Now;
                ViewBag.StartDate = s;
                ViewBag.EndDate = e;
                return null;
            }
            ViewBag.StartDate = start_date.Value;
            ViewBag.EndDate = end_date.Value;
            if (check_report == null)
                check_report = "1";
            string report_filter = "'T','F'";
            if (check_report == "1")
            {
                report_filter = "'T','F'";
            }
            if (check_report == "2")
            {
                report_filter = "'T'";
            }
            if (check_report == "3")
            {
                report_filter = "'F'";
            }
            string sql = @"select a.sec_dept,c.deptname,count(*) nums,sum(isnull(a.loss_money,0)) loss,
                         sum(isnull(a.injury_easy,0)) qs, sum(isnull(a.injury_heavy,0)) zs,sum(isnull(a.died,0)) sw,
                        sum(isnull(b.fact_money,0)) fm,sum(isnull(a.injury_heavy,0)+isnull(a.died,0)+isnull(a.injury_easy,0)) sum_injury
                         from sec_record a,sec_end b,sys_dept c
                         where a.sec_no = b.sec_no 
                         and a.SEC_DEPT = c.deptcode
                         and convert(varchar(10),a.sec_date,120) between '{0}' and '{1}'
                         and is_report in ({2}) and c.use_flag='T'
                         and a.is_end='T'  
                         group by a.sec_dept,c.deptname"
                .FormatWith(start_date.Value.ToDefaultDateString(), end_date.Value.ToDefaultDateString(), report_filter);
            DataTable table = WebcarDataProvider.DB.ExecuteDataTable(sql);
            return table;
        }
        public ActionResult SecSummaryList(DateTime? start_date, DateTime? end_date, string check_report)
        {
            var table = GetSummaryData(start_date, end_date, check_report);
            if (table == null)
                return View();
            return View(model: table);
        }
        #region Edit
       
        [HttpGet]
        public ActionResult Edit(string id,string deptcode)
        {
            SEC_RECORD model = null;
            if (id.IsNotNull())
            {
                model = WebcarDataProvider.DB.SEC_RECORD.Find(id);
            }
            if (model == null)
            {
                model = new SEC_RECORD();
                model.SEC_DEPT = deptcode;
                model.SEC_DATE = DateTime.Now;
                model.IS_END = "F";
            }
            ViewBag.DriverName = null;
            var driver = WebcarDataProvider.DB.BS_EMP.Find(model.DRIVER);
            if (driver != null)
                ViewBag.DriverName = driver.MAN_NAME;
            return View(model:model);
        }
        [HttpPost]
        public ActionResult Edit(SEC_RECORD model)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑安全事故);
            string err="";

            if (CheckCarModel(model, ref err) == false)
            {
                ViewBag.ErrorMessage = err;
                var driver = WebcarDataProvider.DB.BS_EMP.Find(model.DRIVER);
                if (driver != null)
                    ViewBag.DriverName = driver.MAN_NAME;
                return View(model: model);
                
            }

            SEC_RECORD item = null;
            using (var DB = new WebcarContext())
            {
                if (model.SEC_NO.IsNotNull())
                {
                    item = DB.SEC_RECORD.Find(model.SEC_NO);
                }
                else
                {
                    item = new SEC_RECORD();

                    DB.SEC_RECORD.Add(item);
                }
                model.CopyPropertyTo(item);
                if (item.SEC_NO.IsNull())
                    item.SEC_NO = "S" + DB.GetSearialId();
                if (item.IS_END.IsNull())
                    item.IS_END = "F";
                DB.SaveChanges();
            }
            return Success("List", "Sec", new { id = item.SEC_DEPT });
            //return View(model: model);
        }

        bool CheckCarModel(SEC_RECORD model, ref string error)
        {
            if (model.SEC_DEPT.IsNull())
            {
                error = "请选择车辆单位。";
                return false;
            }
            if (model.SEC_DATE.IsNullDateTime())
            {
                error = "请选择事故日期。";
                return false;
            }
            if (model.CAR_NO.IsNull())
            {
                error = "请选择车辆。";
                return false;
            }
            if (model.RECORD_NO.IsNull())
            {
                error = "请选择车辆。";
                return false;
            }
            if (model.DRIVER.IsNull())
            {
                error = "请选择驾驶员。";
                return false;
            } 
            if (model.FROM_TO.IsNull())
            {
                error = "请输入航程起至。";
                return false;
            }
            if (model.SEC_PLACE.IsNull())
            {
                error = "请选择驾驶员。";
                return false;
            }
            if (model.SEC_TYPE.IsNull())
            {
                error = "请选择事故类型。";
                return false;
            }
            if (model.SEC_KIND.IsNull())
            {
                error = "请选择事故程度。";
                return false;
            }
            if (model.SEC_DUTY.IsNull())
            {
                error = "请选择事故责任。";
                return false;
            }
            if (model.SEC_CAUSE.IsNull())
            {
                error = "请输入事故概况。";
                return false;
            }
            return true;
        }
        #endregion

        [HttpGet]
        public ActionResult End(string id)
        {
            var model = WebcarDataProvider.DB.SEC_END.Find(id);
            if (model == null)
            {
                model = new SEC_END();
                model.SEC_NO = id;
                model.END_DATE = DateTime.Now;
                model.PAY_XS = 1;
                model.FACT_MONEY = 0;
            }
            ViewBag.InsureNoList = GetInsureList(id);
            var own_list = GetPayList(id, "T");
            var third_list = GetPayList(id, "F");

            ViewBag.OwnPayList = own_list;
            ViewBag.ThirdPayList = third_list;
            ViewBag.SumMoney = own_list.Sum(a => a.Item2) + third_list.Sum(a => a.Item2);
            return View(model:model);
        }

        [HttpPost]
        public ActionResult End(SEC_END model)
        {
            try
            {
                CurrentUser.EnsurePermission(PermissionManager.编辑安全事故);
                if (model.END_DATE.IsNullDateTime())
                {
                    throw new Exception("请输入结案时间。");
                }

                var own_paylist = this.GetInputPayList("ownpay", "ownpaymoney");
                var third_paylist = this.GetInputPayList("thirdpay", "thirdpaymoney");
                ViewBag.OwnPayList = own_paylist;
                ViewBag.ThirdPayList = third_paylist;

                ViewBag.SumMoney = own_paylist.Sum(a => a.Item2) + third_paylist.Sum(a => a.Item2);
                using (var DB = new WebcarContext())
                {
                    var exists = DB.SEC_END.Find(model.SEC_NO);
                    if (exists == null)
                    {
                        DB.SEC_END.Add(model);
                    }
                    else
                    {
                        model.CopyPropertyTo(exists);
                    }
                    DB.SEC_PAY_DETAIL.Delete(a => a.SEC_NO == model.SEC_NO);
                    this.AddPayDetail(own_paylist, model.SEC_NO, "T");
                    this.AddPayDetail(third_paylist, model.SEC_NO, "F");
                    var sec_record = DB.SEC_RECORD.Find(model.SEC_NO);
                    sec_record.IS_END = "T";
                    sec_record.LOSS_MONEY = (decimal)(own_paylist.Sum(a => a.Item2) + third_paylist.Sum(a => a.Item2));
                    DB.SaveChanges();
                    return Success("List", "Sec", new { id = sec_record.SEC_DEPT });
                }
                
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                ViewBag.InsureNoList = GetInsureList(model.SEC_NO);
                return View(model: model);
            }
            //
        }
        void AddPayDetail(List<Tuple<string,float>> list,string sec_no,string kind)
        {
            foreach (var pay_item in list)
            {
                SEC_PAY_DETAIL pay_detail = new SEC_PAY_DETAIL();
                pay_detail.SEC_NO = sec_no;
                pay_detail.PAY_KIND = kind;
                pay_detail.XH = "G" + WebcarDataProvider.DB.GetSearialId();
                pay_detail.FEE_NAME = pay_item.Item1;
                pay_detail.REAL_MONEY = (decimal)pay_item.Item2;
                WebcarDataProvider.DB.SEC_PAY_DETAIL.Add(pay_detail);
            }
        }
        SelectList GetInsureList(string id)
        {
            var sec_record = WebcarDataProvider.DB.SEC_RECORD.Find(id);

            var insure_list = from p in WebcarDataProvider.DB.BS_INSURE
                              where p.CAR_NO == sec_record.CAR_NO
                              select new
                              {
                                  insure_no = p.INSURE_NO,
                                  insure_no2 = p.INSURE_NO2,
                                  end_date = p.END_DATE.Value
                              };
            var insure_list2 = insure_list.AsEnumerable().Select(p => new Tuple<string, string>(p.insure_no, p.insure_no2 + "," + p.end_date.ToString("yyyy-MM-dd") + "到期")).ToList();
            insure_list2.Insert(0, new Tuple<string, string>("", "--请选择--"));
            return new SelectList(insure_list2, "Item1", "Item2");
        }
        List<Tuple<string,float>> GetInputPayList(string flag,string flag2)
        {
            var pay_item = Request.Form[flag].Split(',');
            var pay_money = Request.Form[flag2].Split(',');
            List<Tuple<string, float>> list = new List<Tuple<string, float>>();
            for (int i = 0; i < pay_item.Length; i++)
            {
                if (pay_item[i].IsNull()) continue;
                Tuple<string, float> pay = new Tuple<string, float>(pay_item[i], pay_money[i].ToFloat());
                list.Add(pay);
            }
            return list;
        }
        
        IEnumerable<Tuple<string, float>> GetPayList(string sec_no, string flag)
        {
            string sql = @"select fee_name,sum(isnull(real_money,0)) real_money 
                 from
                 (select 0 as real_money,base_name as fee_name from v_sec_pay_list
                 union
                 select real_money,fee_name from dbo.SEC_PAY_DETAIL
                 where sec_no = '{0}' and pay_kind='{1}') as a
                 group by fee_name order by fee_name".FormatWith(sec_no,flag);
            DataTable table = WebcarDataProvider.DB.ExecuteDataTable(sql);
            return table.Rows.Cast<DataRow>().Select(a => 
                new Tuple<string, float>(a["fee_name"].ToString(), a["real_money"].ToString().ToFloat())
            );
        }

        public ActionResult EndReport(string id)
        {
            var sec_record = WebcarDataProvider.DB.SEC_RECORD.Find(id);

            ViewBag.RECORD = sec_record;
            var end_record = WebcarDataProvider.DB.SEC_END.Find(id);
            if (end_record == null)
            {
                throw new Exception("未找到结案记录。");
            }
            ViewBag.END_RECORD = end_record;

            var dept = WebcarDataProvider.DB.sys_dept.Find(sec_record.SEC_DEPT);
            ViewBag.DeptName = dept == null ? "未知部门" : dept.deptname;
            var car = WebcarDataProvider.DB.BS_CAR_RECORD.Find(sec_record.CAR_NO);
            ViewBag.CarClassName = car == null ? "未知" : car.car_class_name;
            var driver = WebcarDataProvider.DB.BS_EMP.Find(sec_record.DRIVER);
            ViewBag.DriverName = driver == null ? "" : driver.MAN_NAME;

            var pay_list = from p in WebcarDataProvider.DB.SEC_PAY_DETAIL
                           where p.SEC_NO == id
                           select p;
            ViewBag.PayList = pay_list.ToList();
            return View();
        }
    }
}